package com.woniu.service.impl;

import com.nimbusds.jose.JOSEException;
import com.woniu.dto.LoginRequest;
import com.woniu.dto.LoginResponse;
import com.woniu.entity.Customer;
import com.woniu.entity.Employee;
import com.woniu.entity.Users;
import com.woniu.mapper.CustomerMapper;
import com.woniu.mapper.EmployeeMapper;
import com.woniu.mapper.UsersMapper;
import com.woniu.service.CustomerService;
import com.woniu.service.UserService;
import com.woniu.util.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private UsersMapper usersMapper;
    @Override
    public ResponseUtil login(LoginRequest loginRequest) throws JOSEException {
        // 基础入参校验
        if (loginRequest == null
                || !org.springframework.util.StringUtils.hasText(loginRequest.getAccount())
                || !org.springframework.util.StringUtils.hasText(loginRequest.getPassword())) {
            return ResponseUtil.get(ResponseEnum.USER_LOGIN_FAIL_1);
        }

        // 查询用户
        Customer users = customerMapper.selectByAccount(loginRequest.getAccount());
        if (users == null) {
            return ResponseUtil.get(ResponseEnum.USER_LOGIN_USERNAME_NOMATCH);
        }
        if (users.getStatus() == 2) {
            return ResponseUtil.get(ResponseEnum.USER_LOGIN_FAIL_2);
        }

        // 使用统一的匹配器校验密码（兼容旧的盐+SHA-256 与 BCrypt）
        boolean matched = PasswordHasher.matches(
                loginRequest.getPassword(),
                users.getPassword(),
                users.getSalt()
        );
        if (!matched) {
            return ResponseUtil.get(ResponseEnum.USER_LOGIN_PASSWORD_NOMATCH);
        }

        // 如果当前不是 BCrypt 格式，登录成功后自动升级成 BCrypt 并清空 salt
        String dbPwd = users.getPassword();
        if (dbPwd != null && !(dbPwd.startsWith("$2a$") || dbPwd.startsWith("$2b$") || dbPwd.startsWith("$2y$"))) {
            String newHash = PasswordHasher.bcrypt(loginRequest.getPassword()); // 生成 BCrypt
            users.setPassword(newHash); // 将加密后的密码 存入数据库
            users.setSalt(null);
            customerMapper.updateByPrimaryKeySelective(users);
        }


        HashMap<String, Object> map = new HashMap<>();
        map.put("id", users.getCustomerId());
        map.put("username", users.getUsername());
        map.put("name", users.getName());
        map.put("phone", users.getPhone());
        map.put("email", users.getEmail());
        map.put("token",JwtUtil.getToken( map));

        stringRedisTemplate.opsForValue().set("token"+users.getCustomerId(),JwtUtil.getToken( map),60, TimeUnit.SECONDS);


        return ResponseUtil.get(ResponseEnum.OK, map);
    }
    @Resource
    private EmployeeMapper employeeMapper;
    @Resource
    private RedisTemplate redisTemplateInit;
    /**
     * 后台登录，增加验证码验证
     */
    public ResponseUtil backLogin(Employee employee, String captchaKey, String captchaCode) throws JOSEException {
        // 验证验证码
        if (captchaKey == null || captchaCode == null) {
            return ResponseUtil.get(ResponseEnum.CAPTCHA_EMPTY);
        }

        // 从Redis获取验证码
        String storedCode = (String) redisTemplateInit.opsForValue().get(ConstantUtil.REDIS_CAPTCHA_KEY + captchaKey);
        if (storedCode == null) {
            return ResponseUtil.get(ResponseEnum.CAPTCHA_EXPIRED);
        }

        // 验证验证码是否正确（忽略大小写）
        if (!storedCode.equalsIgnoreCase(captchaCode)) {
            return ResponseUtil.get(ResponseEnum.CAPTCHA_ERROR);
        }

        // 验证成功后删除验证码，防止重复使用
        redisTemplateInit.delete(captchaKey);

        // 原有登录逻辑
        Employee loginUser = employeeMapper.findByUsername(employee.getUsername());
        if (loginUser == null) {
            return ResponseUtil.get(ResponseEnum.USER_LOGIN_USERNAME_NOMATCH);
        } else if (!loginUser.getStatus().equals(1)) {
            return ResponseUtil.get(ResponseEnum.USER_LOGIN_FAIL_2);
        } else if (!loginUser.getPassword().equals(employee.getPassword())) {
            return ResponseUtil.get(ResponseEnum.USER_LOGIN_PASSWORD_NOMATCH);
        } else {
            loginUser.setPassword(null);
            HashMap<String, Object> map = new HashMap<>();
            map.put("username", loginUser.getUsername());
            map.put("employeeId", loginUser.getEmployeeId());
            String jwt = JwtUtil.getToken(map);
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("token", jwt);
            resultMap.put("userInfo", loginUser);
            redisTemplateInit.opsForValue().set(ConstantUtil.REDIS_JWT_KEY + loginUser.getEmployeeId(),
                    jwt, 30, TimeUnit.MINUTES); // 修正时间单位为分钟
            return ResponseUtil.get(ResponseEnum.USER_LOGIN_SUCCESS, resultMap);
        }
    }
}
